#include "ActionThread.h"

#include <QtNetwork>

ActionThread::ActionThread(int socketDescriptor, UserManager* userManager, QObject *parent) :
	QThread(parent),
	_socketDescriptor(socketDescriptor),
	_userManager(userManager)
{
	connect(&_socket,SIGNAL(disconnected()),SLOT(onDisconnected()));
}

void ActionThread::run()
{
	if (!_socket.setSocketDescriptor(_socketDescriptor)) {
		emit error(_socket.error());
		return;
	}
	sendData(QString("Hello, world").toAscii());

	emit writeData("Connected: " + _socket.peerAddress().toString());

	while(1){
		if(_socket.waitForReadyRead(10000)){
			onBytesReady();
		}
	}

	_socket.disconnectFromHost();
	_socket.waitForDisconnected();
}

void ActionThread::sendData(QByteArray data){
	_socket.write(data);
}

void ActionThread::onBytesReady(){
	QByteArray data = _socket.readAll();

	/// TODO: check CRC

	CommandType cmd = (CommandType) data.at(0);
	data.remove(0,1);

	switch(cmd){
	case Register:{
		User user(data);
		_userManager->addUser(&user);
		emit writeData("User registered. Id=" + QString().setNum(user.getId()) + "Name=" + user.getName());
		break; }
	case Hello:{
		User* user = _userManager->getUserById(data.toInt());
		if(user == NULL) return;
		user->setState(User::UserOnline);
		emit writeData("User " + user.getName() + " is online.");
		break; }
	case AccountData:
		/// TODO: change account data
		break;
	case SetStatus:
		break;
	case UsersList:
		break;
	case GetUserData:
		break;
	case Message:
		break;
	case Message2:
		break;
	case SendFile:
		break;
	case FileSubmit:
		break;
	case FileReady:
		break;
	case FileTransmit:
		break;
	case GetFile:
		break;
	default: return;
	}
}

void ActionThread::onDisconnected(){
	emit writeData("Disconnected");
}
